import { useEffect, useState, useMemo } from 'react';
import { message } from 'antd';
import { useNavigate } from 'react-router-dom';
import { stringify } from 'qs';
import moment from 'moment';
import FormRender from '@/components/FormRender';
import CommonTable from '@/components/CommonTable';
import { useResize } from '@/hooks/useResize';
import CommonPagination from '@/components/CommonPagination';
import RelativeModal from './component/RelativeModal';
import AccountDetail from './component/AccountDetail';
import OperaBtnRender from '@/components/OperaBtnRender';
import { getFormItem } from './config.js';
import { handleExportExcel, handleExportExcel2, formatAmount, customTrimFunc } from '@/utils/utils.jsx';
import { getUserAccountListOp, getBusiAccountListOp, getStorageAccountListOp, getBillDetailsOp, getHistoryUserAccountListOp } from '../service';
import { getCurrentUser } from '@/utils/authority';

const dateFormat = 'YYYY-MM-DD HH:mm:ss';

const initQuery = {
	time: [moment().startOf('day').subtract(14, 'days'), moment().endOf('day')],
}

//支付方式
const payMethod = [
	{ text: '余额', value: '1' },
	{ text: '转账充值', value: '3' },
	{ text: '支付宝', value: '2' },
	{ text: '微信', value: '4' },
	{ text: '银行卡充值', value: '8' },
]

const transTypeList = [
	{ text: '下单付款', value: '4' },
	{ text: '修改商品', value: '8,13' },
	{ text: '拿货换货', value: '43' },
	{ text: '订单运费', value: '5' },
	{ text: '拿货改价', value: '12' },
	{ text: '订单退款', value: '9' },
	{ text: '充值', value: '2' },
	{ text: '提现', value: '3' },
	{ text: '订单返审核', value: '23' },
	{ text: '订单作废', value: '22' },
	{ text: '手续费补贴', value: '24' },
	{ text: '手续费', value: '14' },
	{ text: '营销费用', value: '1' },
	{ text: '转账充值', value: '16' },
	{ text: '更换包装', value: '21' },
	{ text: '仓储服务费', value: '25' },
	{ text: '账期还款', value: '26' },
	{ text: '仓内拆单', value: '27' },
	{ text: '采购付款', value: '28' },
	{ text: '采购作废', value: '29' },
	{ text: '采购退款', value: '30' },
	{ text: '拆分装箱', value: '33' },
	{ text: '线下备货', value: '34' },
	{ text: '取消线下备货', value: '35' },
	{ text: '财审结算', value: '36' },
	{ text: '无采购入库', value: '37' },
	{ text: '抵扣备货', value: '39' },
	{ text: '取消抵扣备货', value: '40' },
	{ text: '抵扣退款', value: '41' },
	{ text: '商户账期退款', value: '42' },
	{ text: '转正常单', value: '46' },
	{ text: '其它', value: '17,20' },//场景：挂账分账
]

const transTypeListBus = [
	{ text: '拿货收款', value: '6' },
	{ text: '手续费', value: '14' },
	{ text: '商家收款', value: '4' },
	{ text: '手续费补贴', value: '24' },
	{ text: '订单退款', value: '9' },
	{ text: '营销费用', value: '1' },
	{ text: '取消备货', value: '10' },
	{ text: '账期还款', value: '26' },
	{ text: '充值', value: '2' },
	{ text: '采购收款', value: '28' },
	{ text: '转账充值', value: '16' },
	{ text: '提现', value: '3' },
	{ text: '其它', value: '17' },//场景：挂账分账
]

// 支付环节(仓储用户)
const tradeTypeStorage = [
	{ text: '包材费用', value: '15' },
	{ text: '订单运费', value: '5' },
	{ text: '订单退款', value: '9' },
];

const AccountDetailList = ({ type, accountMsg, infoKey, headerHeight, dispatch, tradeNo, handleClearTradeNo, stepObj, handleGoHistory }) => {

	const [record, setRecord] = useState({});//操作当前行信息

	const [filter, setFilter] = useState({});//表格参数

	const [visible, setVisible] = useState(undefined);

	const [payList, setPayList] = useState([]);

	const [updateKey, setUpdateKey] = useState(0);

	const [accountDetail, setAccountDetail] = useState({});

	const navigate = useNavigate();

	const [pages, setPages] = useState({
		current: 1,
		pageSize: 10,
		total: 0,
	})

	const { step } = stepObj; //1账户余额 4历史账单查询

	const [query, setQuery] = useState({ ...initQuery });

	//监听变更
	const { el: headerEl, height: formHeight, onResize } = useResize();

	//表单数据
	const formArr = useMemo(() => {
		return getFormItem(type);
	}, [type])


	// const urlParams = useLocation();

	// if (urlParams.query && urlParams.query.payOrder) {
	// 	tradeNo = urlParams.query.payOrder;
	// }

	//userType是用户类型，1是用户，2是商户，3是仓储
	const { userType = 2 } = accountMsg;

	useEffect(() => {
		updateKey && getAccountListFunc();
	}, [updateKey])

	useEffect(() => {
		if (accountMsg.userType) {
			setPages({ ...pages, current: 1 });
			setFilter({});
			setUpdateKey(updateKey + 1);
		}
	}, [type, infoKey, accountMsg, step])

	//表格数据
	const getAccountListFunc = async () => {
		const obj = getCurrentUser().accountExtend || {};
		START_LOADING();
		const params = customTrimFunc({
			...query,
			...filter,
			current: pages.current,
			size: pages.pageSize,
		});

		if (params.time && !tradeNo) { //跳转过来的不带时间查询
			params.timeStart = moment(params.time[0]._d).format(dateFormat);
			params.timeEnd = moment(params.time[1]._d).format(dateFormat);
		}
		params.time = undefined;

		if (tradeNo) {
			params.tradeNo = tradeNo;
			setQuery({ tradeNo: tradeNo });
		}
		let res;
		if (type == 1) {
			params.accountNo = obj.accountNo ? obj.accountNo : localStorage.getItem('ACCOUNT_NO');
			if (params.transTypes) {
				params.transTypes = params.transTypes;
			}
			if (params.orderType) {
				params.orderType = Number(params.orderType);
			}
			res = await getUserAccountListOp(params);
		} else {
			params.incomeAccountNo = accountMsg.merchantNo;
			res = await getBusiAccountListOp(params);
		}
		const { success, data } = res;
		if (success) {
			const { records, total } = data
			setPayList(records)
			setPages({ ...pages, total });
		} else {
			setPayList([])
			setPages({ ...pages, total: 0, current: 1 });
		}
		tradeNo && handleClearTradeNo();
		END_LOADING()
	}

	const handleRelative = (val) => {
		setRecord(val);
		setVisible('relative');
	}

	//用户展示列
	const columns1 = [
		{
			title: '序号',
			dataIndex: 'index',
			key: 'index',
			width: 60,
			render: (t, r, i) => i + 1
		},
		{
			title: '流水单号',
			dataIndex: 'tradeNo',
			key: 'tradeNo',
			width: 220,
			render: (text, record) => <>
				<span className='common-color3' style={{ fontWeight: 500 }}>{text}</span>
				<p>{record.paySuccessTime}</p>
			</>
		},
		{
			title: '支付方式',
			dataIndex: 'payMethName',
			key: 'payMethName',
			filteredValue: filter.payMeth ? [filter.payMeth] : null,
			filters: payMethod,
			filterMultiple: false,
			width: 120,
			render: text => <span className='common-color4'>{text}</span>
		},
		{
			title: '支付环节',
			dataIndex: 'transTypeName',
			key: 'transTypeName',
			width: 120,
			filteredValue: filter.transTypes ? [filter.transTypes] : null,
			filters: transTypeList,
			filterMultiple: false,
			render: text => <span className='common-color4'>{text}</span>
		},
		{
			title: '收支金额（元）',
			dataIndex: 'amountYuan',
			key: 'amountYuan',
			width: 140,
			filterMultiple: false,
			render: (text, { costTypeName }) => {
				if (costTypeName == '收入') {
					return <span className='common-color9' style={{ fontWeight: 500 }}>+{formatAmount(Number(text))}</span>
				} else {
					return <span className='common-color10' style={{ fontWeight: 500 }}>{formatAmount(Number(text))}</span>
				}
			}
		},
		{
			title: '当前余额',
			dataIndex: 'currentAvailBalanceYuan',
			key: 'currentAvailBalanceYuan',
			width: 120,
			render: text => <span className='common-color4'>{formatAmount(text)}</span>
		},
		{
			title: '订单类型',
			dataIndex: 'orderTypeName',
			key: 'orderTypeName',
			width: 120,
			render: text => <span className='common-color4'>{text}</span>
		},
		{
			title: '说明',
			dataIndex: 'remark',
			key: 'remark',
			width: 120,
			render: text => <span className='common-color4'>{text}</span>
		},
		{
			title: '操作',
			dataIndex: 'operator',
			key: 'operator',
			width: 100,
			fixed: 'right',
			render: (text, record) => <span className='common-color1' style={{ cursor: 'pointer' }} onClick={() => handleRelative(record)}>关联订单号</span>
		}
	];

	//仓储展示列
	const columns2 = [
		{
			title: '序号',
			dataIndex: 'index',
			key: 'index',
			width: 60,
			render: (t, r, i) => i + 1
		},
		{
			title: '支付单号',
			dataIndex: 'payOrderSn',
			key: 'payOrderSn',
			width: 200,
			render: text => <span className='common-color3' style={{ fontWeight: 500 }}>{text}</span>
		},
		{
			title: '支付方式',
			dataIndex: 'payMethName',
			key: 'payMethName',
			width: 120,
			render: text => <span className='common-color4'>{text}</span>
		},
		{
			title: '支付环节',
			dataIndex: 'transTypeName',
			key: 'transTypeName',
			width: 120,
			filteredValue: filter.transTypes ? [filter.transTypes] : null,
			filters: tradeTypeStorage,
			filterMultiple: false,
			render: text => <span className='common-color4'>{text}</span>
		},
		{
			title: '收支金额（元）',
			dataIndex: 'amountYuan',
			key: 'amountYuan',
			width: 140,
			render: (text, { costTypeName }) => {
				if (costTypeName == '收入') {
					return <span className='common-color9' style={{ fontWeight: 500 }}>+{formatAmount(Number(text))}</span>
				} else {
					return <span className='common-color10' style={{ fontWeight: 500 }}>{formatAmount(Number(text))}</span>
				}
			}
		},
		{
			title: '收入/支出',
			dataIndex: 'costTypeName',
			key: 'costTypeName',
			width: 120,
			// filters: [
			//   { text: '收入', value: '收入' },
			//   { text: '支出', value: '支出' },
			// ],
			render: text => <span className='common-color4'>{text}</span>
		},
		{
			title: '付款时间',
			dataIndex: 'paySuccessTime',
			key: 'paySuccessTime',
			width: 160,
			render: text => <span className='common-color4'>{text}</span>
		},
		{
			title: '备注',
			dataIndex: 'remark',
			key: 'remark',
			width: 120,
			render: text => <span className='common-color4'>{text}</span>
		},
		{
			title: '操作',
			dataIndex: 'operator',
			key: 'operator',
			width: 100,
			fixed: 'right',
			align: 'center',
			render: (text, { payOrderSn, transTypeName }) => {
				if (['充值', '手续费', '手续费补贴', '手续费补助'].includes(transTypeName)) {
					return '-';
				} else {
					return <span className='common-color1' style={{ cursor: 'pointer' }} onClick={() => jumpAndSearch(payOrderSn)}>查看详情</span>
				}
			}
		}
	];

	//商户展示列
	const columns3 = [
		{
			title: '序号',
			dataIndex: 'index',
			key: 'index',
			width: 60,
			render: (t, r, i) => i + 1
		},
		{
			title: '交易时间',
			dataIndex: 'paySuccessTime',
			key: 'paySuccessTime',
			width: 160,
			render: text => <span className='common-color4'>{text}</span>
		},
		{
			title: '交易描述',
			dataIndex: 'subject',
			key: 'subject',
			width: 120,
			render: text => <span className='common-color4'>{text}</span>
		},
		{
			title: '支付环节',
			dataIndex: 'transTypeName',
			key: 'transTypeName',
			width: 120,
			filteredValue: filter.transTypes ? [filter.transTypes] : null,
			filters: transTypeListBus,
			filterMultiple: false,
			render: text => <span className='common-color4'>{text}</span>
		},
		{
			title: '收支金额（元）',
			dataIndex: 'amountYuan',
			key: 'amountYuan',
			width: 140,
			// filteredValue: filter.costType ? [filter.costType] : null,
			// filters: [
			//   { text: '收入', value: '1' },
			//   { text: '支出', value: '2' },
			// ],
			// filterMultiple:false,
			render: (text, { costTypeName, settleAmount }) => {
				if (costTypeName == '收入') {
					return <div>
						<div style={{ fontWeight: 500, color: settleAmount > 0 ? 'orange' : '#FF2D51' }}>+{formatAmount(Number(text))}</div>
						<div className='common-color10'>{settleAmount > 0 ? `银行结算中（${settleAmount}）` : ''}</div>
					</div>
				} else {
					return <div>
						<span className='common-color10' style={{ fontWeight: 500, color: settleAmount > 0 ? 'orange' : '#00B87C' }}>{formatAmount(Number(text))}</span>
						<div className='common-color10'>{settleAmount > 0 ? `银行结算中（${settleAmount}）` : ''}</div>
					</div>
				}
			}
		},
		{
			title: '当前余额',
			dataIndex: 'currentAvailBalanceYuan',
			key: 'currentAvailBalanceYuan',
			width: 120,
			render: text => <span className='common-color4'>{formatAmount(text)}</span>
		},
		{
			title: '收入/支出',
			dataIndex: 'costTypeName',
			key: 'costTypeName',
			width: 140,
			render: text => <span className='common-color4'>{text}</span>
		},
		{
			title: '订单类型',
			dataIndex: 'orderTypeName',
			key: 'orderTypeName',
			width: 120,
			render: text => <span className='common-color4'>{text}</span>
		},
		{
			title: '说明',
			dataIndex: 'remark',
			key: 'remark',
			width: 120,
			render: text => <span className='common-color4'>{text}</span>
		},
		{
			title: '操作',
			dataIndex: 'operator',
			key: 'operator',
			width: 100,
			fixed: 'right',
			render: (text, record) => <span className='common-color1' style={{ cursor: 'pointer' }} onClick={() => handleDetail(record)}>详情</span>
		}
	];

	//查看详情跳转
	const jumpAndSearch = (payOrderSn) => {
		navigate("/account/capital", { state: { query: payOrderSn, userIdentity: type } });
	}

	//点击查看详情
	const handleDetail = async (record) => {
		//获取账单详情
		START_LOADING();
		const { data, success } = await getBillDetailsOp({ payOrderSn: record.payOrderSn });
		if (success) {
			setAccountDetail(data);
			setRecord(record);
			setVisible('detail');
		} else {
			setRecord({});
		}
		END_LOADING();
	}

	//导出功能
	const exportExcel = () => {
		const { total } = pages;
		const obj = getCurrentUser().accountExtend || {};
		if (total) {
			const nums = Math.ceil(total / 10000);
			message.info(`即将为您导出${nums}张Excel，请稍候...`);

			START_LOADING()
			const params = { ...query, ...filter }
			if (params.time) {
				params.timeStart = moment(params.time[0]._d).format(dateFormat);
				params.timeEnd = moment(params.time[1]._d).format(dateFormat);
				params.time = undefined
			}
			params.current = 1;
			params.size = 10000;
			params.accountNo = obj.accountNo ? obj.accountNo : localStorage.getItem('ACCOUNT_NO');
			const handleExport = () => {
				if (type == 1) {
					handleExportExcel2(`/zjf-pays-bill/user/bill/detail/excel`, params, '用户账单余额明细.xlsx', commonCallback)
				} else {
					if (userType == 2) {//商户账单
						handleExportExcel(`/zjf-pays-bill/merchantpayorder/excelPageMerchantPayOrderByErp?${stringify(params)}`, '商户账单余额明细.xlsx', commonCallback)
					} else {//仓储账单
						handleExportExcel(`/zjf-oms/payorder/payOrderExcelWms?${stringify(params)}`, '商户账单余额明细.xlsx', commonCallback)
					}
				}
			}

			const commonCallback = () => {
				params.current++;
				if (params.current <= nums) {
					message.info(`总计${nums}张，即将为您导出第${params.current}张`);
					handleExport();
				}
				END_LOADING();
			}
			handleExport();

		} else {
			message.info('暂无可导出的数据！')
		}
	}

	//表单渲染组件
	const FormRenderProps = {
		query,
		formArr,
		formConfig: {
			name: 'child-account-manage-form',
			style: { margin: '16px 0' }
		},
		clickSearch(val) {
			setQuery(val);
			setPages({ ...pages, current: 1 });
			setUpdateKey(updateKey + 1);
			//这里触发余额区域重新查询
			dispatch({
				type: 'addBalance'
			})
		},
		clickReset() {
			setQuery({ ...initQuery });
			setPages({ ...pages, current: 1 });
			setUpdateKey(updateKey + 1);
		},
	}

	const getColumns = () => {
		if (type == 1) {
			return columns1;
		} else {
			if (userType == 2) {
				return columns3;
			}
			return columns2;
		}
	}

	const getScrollWidth = () => {
		if (userType == 1) {
			return 1120;
		} else if (userType == 3) {
			return 1140;
		} else {
			return 1200;
		}
	}

	const scrollHeight = [2, 3].includes(accountMsg.userType) ? headerHeight + formHeight + 312 : headerHeight + formHeight + 272

	const TableProps = {
		data: payList,
		columns: getColumns(),
		scroll: { x: getScrollWidth(), y: `calc(100vh - ${scrollHeight}px)` },
		handleRowKey(record) {
			return record.payOrderSn + record.id;
		},
		onChange(_, filter) {
			const { payMethName, transTypeName, amountYuan } = filter
			const params = {}
			if (payMethName) {
				params.payMeth = payMethName[0]
			}
			if (transTypeName) {
				params.transTypes = transTypeName[0]
			}
			if (amountYuan) {
				params.costType = amountYuan[0]
			}
			setFilter(params);
			setPages({ ...pages, current: 1 });
			setUpdateKey(updateKey + 1);
		}
	};

	//关联订单号弹窗
	const RelativeModalProps = {
		visible: true,
		record,
		handleClose() {
			setRecord({});
			setVisible(undefined);
		}
	}

	const PageProps = {
		pagination: pages,
		style: { marginTop: '12px'},
		handleChange(current, size) {
			setPages({
				...pages,
				current,
				pageSize: size
			})
			setUpdateKey(updateKey + 1);
		},
	}

	const AccountDetailProps = {
		obj: accountDetail,
		record,
		visible: true,
		handleCancel() {
			setRecord({});
			setAccountDetail({});
			setVisible(undefined);
		}
	}

	//操作按钮
	const btnArr = [
		{ elType: 'button', text: '表格导出', onClick: exportExcel }
	]

	return (
		<>
			<div ref={headerEl}>
				<FormRender {...FormRenderProps} />
			</div>
			<div className='global-page-wrap'>
				<OperaBtnRender style={{ marginBottom: '12px' }} btnArr={btnArr} />
				<CommonTable {...TableProps} />
				<CommonPagination {...PageProps} />
			</div>
			{visible == 'relative' && <RelativeModal {...RelativeModalProps} />}
			{visible == 'detail' && <AccountDetail {...AccountDetailProps} />}
		</>
	)
};

export default AccountDetailList
